package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.HupRegion;
import com.ruoyi.system.service.IHupRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/region")
@Slf4j
public class HupRegionController extends BaseController {

    @Resource
    private IHupRegionService hupRegionService;

    // 根据 ID 获取地区
    @GetMapping("/getRegionById")
    public AjaxResult getRegionById(@RequestParam Integer id) {
        try {
            HupRegion region = hupRegionService.getRegionById(id);
            return success(region);
        } catch (Exception e) {
            log.error("获取地区失败: {}", e.getMessage());
        }
        return error();
    }

    // 获取所有省份
    @GetMapping("/provinces")
    public AjaxResult getProvinces() {
        try {
            List<HupRegion> provinces = hupRegionService.getProvinces();
            return success(provinces);
        } catch (Exception e) {
            log.error("获取省份失败: {}", e.getMessage());
        }
        return error();
    }

    // 根据父 ID 获取子地区
    @GetMapping("/children")
    public AjaxResult getChildrenRegioRequestParam(@RequestParam  Integer pid) {
        try {
            List<HupRegion> children = hupRegionService.getChildrenRegions(pid);
            return success(children);
        } catch (Exception e) {
            log.error("获取子地区失败: {}", e.getMessage());
        }
        return error();
    }

    // 根据名称搜索地区
    @GetMapping("/search")
    public AjaxResult searchRegions(@RequestParam String keyword) {
        try {
            List<HupRegion> regions = hupRegionService.searchRegions(keyword);
            return success(regions);
        } catch (Exception e) {
            log.error("搜索地区失败: {}", e.getMessage());
        }
        return error();
    }

    // 根据经纬度获取所在地区
    @GetMapping("/lnglat")
    public AjaxResult getRegionByLngLat(@RequestParam String lng, @RequestParam String lat) {
        try {
            HupRegion region = hupRegionService.getRegionByLngLat(lng, lat);
            return success(region);
        } catch (Exception e) {
            log.error("根据经纬度获取地区失败: {}", e.getMessage());
        }
        return error();
    }
}